<template>
  <div id="app">
    <div v-if="isLogin">
      <app-header ref="appheader"></app-header><!--//电话状态和通话时长-->
      <sidebar></sidebar> <!--侧边栏-->
      <div :class="$style.background">
        <breadcrumb></breadcrumb>
        <div :class="$style.content" :style="customStyle">
          <keep-alive>
            <router-view @onCustomStyle="_isCustomStyle" v-if="$route.meta.keepAlive"></router-view>
          </keep-alive>
          <router-view @onCustomStyle="_isCustomStyle" v-if="!$route.meta.keepAlive"></router-view>
        </div>
      </div>
    </div>

    <login v-if="!isLogin"></login>
    <call-in></call-in><!--电话服务-->

    <!-- <Drag v-if="isLogin">
      <iframe :class="$style.chatRoom" :src="chatRoomBaseUrl + cuKfid" frameborder="0"></iframe>
    </Drag> -->
    <!-- <remark-dialog ref="remark"></remark-dialog> -->
    <call-time v-if="isLogin"></call-time><!--通话时长-->
    <!-- <el-dialog title="呼叫未接通的通话内容" :visible.sync="wjt.dialogVisible" :close-on-click-modal="false">
      <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="wjt.content">
      </el-input>
      <p :class="$style.txtRight">
        <el-button type="primary" @click="handleSubmitWJT">提交</el-button>
      </p>
    </el-dialog> -->
  </div>
</template>

<script>
import { cookie } from 'vux'
import Login from './pages/login/index.vue'
import AppHeader from './components/header/index.vue'
import Sidebar from './components/sidebar/index.vue'
import Breadcrumb from './components/breadcrumb/index.vue'
import CallIn from './components/callin/index.vue'
// import Drag from './components/drag/index.vue'
// 备注弹窗
// import RemarkDialog from './components/remark/index.vue'
// 通话时长
import CallTime from './components/callTime/index.vue'
export default {
  name: 'app',
  components: {
    AppHeader,
    Sidebar,
    Breadcrumb,
    Login,
    CallIn,
    // Drag,
    // RemarkDialog,
    CallTime
  },
  data() {
    // const url = 'http://122.228.132.78:885/w6h8y3_n7s4d/customerchat.aspx?kfid='
    const url = 'http://i.wsloan.com/w6h8y3_n17s4d/customerchat.aspx?kfid='
    return {
      customStyle: null,
      chatRoomBaseUrl: url,
      seatsKf:{},
    }
  },
  computed: {
    //是否登录
    isLogin() {
      return this.$store.getters.getIsLogin //默认状态是false
    },
    userInfo() {
      return this.$store.getters.getUserInfo //默认用户信息为空
    },
    wsData() {
      return websocket.data
    },
    cuKfid() {
      const  {userName,id } = this.$store.getters.getUserInfo  //拿到用户信息
      return  this.$store.getters.getUserInfo.id  //返回登陆用户id
      // return '17'
    },
    getGroup(){
      return this.$store.getters.getGroup //默认用户目标 触发getter拿到当前用户
    }
  },
  watch: {
    wsData(val) {
      
      if (websocket.state === 1) {
        if (val.action === 'hangup') {
          this.hangupHandler(val)
          return
        }
        // 全局监听物理呼出
        if (val.cmd === 'callout') {
          /**
           * 挂机的整体逻辑：
           * 无论物理挂机还是软挂机都实现监听，挂机的过程从发送ajax给后台获取正确内容以后开始，
           * 挂机开始，会强制进入通话详情页面，并给与填写通话内容的提示，
           * 两种情况：
           * 1.若从非通话详情页面挂机，则进入通话详情并给予填写通话内容的提示
           * 2.若在通话详情页面挂机，则直接给予填写通话内容的提示
           * 此时进入通话详情页面，则不能再进入其他页面，必须要填写完通话内容才可以进入其他页面
          */
          this.calloutRetHandlerGobal(val)
        }
        if (val.action == 'openseatlist') {
          this.seatsHandler(val)
        }
        if (val.action == 'calllist') {
          this.callsHandler(val)
        }
        if(val.action == 'openqueues'){
          this.queuesHandler(val)
        }
      }
    },
    isLogin(val){
      if(val){
        // 获取token重新初始化ajax方法
        console.log('用户信息', this.$store.getters.getUserInfo)
        this.getLineup();

        this.getKf();
        //更新当前组的所有客服
        this.getCurGroup()

        myws.init(this.userInfo);
      }
      if(this.userInfo.power < 3 || this.userInfo.power === 5){
       this.getSeat()
      }
    },
  },
  methods: {
    _isCustomStyle(customStyle) {
      if (customStyle) {
        this.customStyle = customStyle
      }
    },
    hangupHandler(val) {
      const {userGroup} = this.userInfo
      const initCallMsg = {
        callType: '',
      }
      if (val.result === '0') {
        // if(userGroup === '业务组'){
        this.$store.dispatch('updateCallMsg',initCallMsg)
        // }
        websocket.pickup = false
        websocket.outPhone = ''
        // 添加通话提示信息
        this.$store.dispatch('updateCallInfo','通话尚未建立连接')
        // 更新挂机行为
        this.$store.dispatch('updateIsHangup',true)

        return
      }
      this.$toast({
        message: '未成功挂断'
      })
    },
    calloutRetHandlerGobal(val) {
      const { id, action, phone, result, recordfile } = val
      let v1 = id,
        v2 = action,
        v3
      websocket.id = v1
      if (action === "out") { //外呼RES
        v3 = result
        if (result === '2') {
          this.$store.dispatch('updateCallMsg', { callType: '' })
          // this.$toast({
          //   message: '电话未打通'
          // })
          return
        }
      } else if (action === "call") { //外线接听开始通话
        v3 = recordfile
      } else if (action === "noanswer") { //呼出未接通结束
        websocket.outPhone = ''
        // this.$toast({
        //   message: '通话未接通'
        // })
      } else if (action === "end") { //呼出接听后结束
        websocket.outPhone = ''
        // this.$toast({
        //   message: '通话结束'
        // })
        // 添加通话提示信息
        this.$store.dispatch('updateCallInfo','通话结束')
      }
      this.ajaxInfo(phone, v1, v2, v3)
    },
    // 通话状态信息
    seatsHandler(data){
      // console.log('updateSeats:', data)
      this.$store.dispatch('updateSeats', data.seatlist)
    },
    queuesHandler(data){
      this.$store.dispatch('updateQueues', data.queues)
    },
    callsHandler(data){
      // let tmpa = []
      this.$store.dispatch('updateCalls', data.calllist)
    },
    async getSeat() {
      
      // 与websock，传过来的进行匹配，
      let { data } = await this.$get(this, {
        api: 'ajaxapi/man_age.do', data: {
        }
      })
      
      if (data.state === 0) {
        this.seatsKf = data.content;
        this.$store.state.user.seatKf=this.seatsKf
        
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    //
    async getLineup() {
      // 获得组id: 组名字
      let { data } = await this.$get(this, {
        api: 'ajaxapi/ipcczb.do', data: {
        }
      })
      if (data.state === 0) {
        this.$store.dispatch('updateGroup', data.content)
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    async getKf() {
      // 已筛选客服，back-log,call,call-total
      const { userGroupId, power } = this.$store.getters.getUserInfo
      let { data } = await this.$get(this, {
        api: 'ajaxapi/loadkf.do',
        data: {
          // sessionId: this.userInfo.sessionId
          groupId: power !== 1 ? userGroupId : ''
        }
      })
      if (data.state === 0) {
        this.$store.dispatch('updateKf', data.content)
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    async getCurGroup() {
      try {
        const { userGroupId } = this.$store.getters.getUserInfo
        const { data } = await this.$get(this, {
          api: 'ajaxapi/loadAllKf.do',
          data: {
            groupId: userGroupId
          }
        })
        if (data.state === 0) {
          this.$store.dispatch('updateCurGroup', data.content)
        }
      } catch (e) {
        this.$warn('系统ajaxapi/loadAllKf.do接口报错')
      }
    },
    async ajaxInfo(m, v1, v2, v3) {
      try {
        const {
          id,
          usertel,
          userGroupId,
          userGroup
        } = this.userInfo
        m = m.replace(/(^\s*9?|\s*$)/g, '')  //消除前后空白符以及可能出现出现0，9
        const daida = this.$store.getters.daida
        const {
          data
        } = await this.$get(this, {
            api: 'ajaxapi/callout.do',
            data: {
              // 添加待打的相关字段
              id:daida && daida.id,
              type:daida && daida.type,
              //
              flag: 0,
              adminid: id,
              yhm: usertel,
              groupId: userGroupId,
              mobile: m,
              callid: v1,
              callinaction: v2,
              actionresult: v3,
            },
          })
        if (v2 === 'call' && data.state === 0) {
          this.$toast({
            message: '开始通话'
          })
          // 添加通话提示信息
          this.$store.dispatch('updateCallInfo','通话已建立连接')
          // 更新挂机行为
          this.$store.dispatch('updateIsHangup',false)
          // 由于不限制提交通话内容，导致未提交通话内容之前仍可以打电话，作如下处理
          const callMsg = {
            telMsg: data.content,
            leadInMsg: data.content,
            mobile: m,
            callType: 'callout',
            curRecordFile: v3,
            createdTime: Date.now(),
            serviceForm: {
              que1: '',
              que2: '',
              content: '',
            }
          }

          // 新功能添加--通话详情标签页
          // if(userGroup !== '业务组'){
          if(userGroup === '答疑组'){
            const tmpo = Object.assign([],this.$store.getters.callList)
            tmpo.data.push(callMsg)
            tmpo.curIndex++
            this.$store.dispatch('updateCallList', tmpo)
          }
          //

          this.$store.dispatch('updateCallMsg', callMsg)
          //

          //
          websocket.outPhone = m
          websocket.pickup = true
          // 业务组不跳详情页
          if(userGroup === '业务组' || userGroup === '回访组'){
            return
          }
          this.$router.push('/call-center/call-detail')
          return
        }

        if (data.state === 0 && v2 === 'noanswer') {
          websocket.outPhone = ''
          websocket.pickup = false
          this.$store.dispatch('updateCallMsg', { callType: '' })

          // 添加通话提示信息
          this.$store.dispatch('updateCallInfo','通话未接通')

          // 挂机的待打尾处理
          this.$store.dispatch('updateDaida', null)
          // 未接通处理
          // this.wjt.dialogVisible = true
          // this.wjt.content = ''
          // const state = this.$refs['appheader'].value
          // if( state === '在线'){
          //   this.wjt.state = this.$refs['appheader'].value
          //   this.$refs['appheader'].value = '暂离'
          // }
          return
        }
        // if (data.state === 0 && v2 === 'end') {
        //   websocket.outPhone = ''
        //   websocket.pickup = false
        //   this.$store.dispatch('updateCallMsg', { callType: '' })

        //   return
        // }
      } catch (e) {
        this.$warn('系统ajaxapi/callout.do接口报错')
      }
    },
  },
  mounted() {
    const callMsg = window.localStorage.getItem('callMsg')
    if (callMsg) {
      this.$store.dispatch('updateCallMsg', JSON.parse(callMsg))
    }
    const callList = window.localStorage.getItem('callList')
    if (callList) {
      this.$store.dispatch('updateCallList', JSON.parse(callList))
    }
    if(this.userInfo.power < 3 || this.userInfo.power === 5){
      this.getSeat()
    }
    //
    // this.test()
  },
}

</script>
<style lang="scss" module>
.background {
  background: #f5f8fb;
  box-sizing: border-box;
  padding: 20px;
  padding-left: 250px;
  padding-right: 60px;
  height: calc(100vh - 80px);
  position:relative;
}

.content {
  background: #fff;
  height: calc(100% - 10px);
  width: 100%;
  box-sizing: border-box;
  margin-top: 10px;
  overflow-y: scroll;
  border-radius: 5px;
  border: 1px solid #dddfe6;
}

.chatRoom {
  width: 100%;
  height: 100%;
}
.txtRight{
  text-align:right;
  margin-top:10px;
}
</style>

<style src="../style/index.scss" lang="scss"></style>
